package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConst;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SetmealServiceImpl implements SetmealService {


    @Autowired
    SetmealDao dao;

    @Autowired
    JedisPool jedisPool;

    @Override
    @Transactional
    public void add(Integer[] checkgroupIds, Setmeal setmeal) {
        dao.add(setmeal);

        if (setmeal.getId()!=null&&checkgroupIds!=null&&checkgroupIds.length>0){
            for (Integer checkgroupId : checkgroupIds) {

                dao.set(setmeal.getId(),checkgroupId);
            }
        }
        jedisPool.getResource().sadd(RedisConst.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());

    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Setmeal> page = dao.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page);
    }

    @Override
    public List<Setmeal> findAll() {
        List<Setmeal> setmealList = dao.findAll();
        return setmealList;
    }

    @Override
    public Setmeal findById(Integer id) {

        return dao.findById(id);
    }

    @Override
    public Map<String, Object> getSetmealReport() {

        List<Map<String,Object>> mapList = dao.getSetmealReport();
        List<Object> setmealNames = new ArrayList<>();
        for (Map<String, Object> map : mapList) {
            Object name = map.get("name");
            setmealNames.add(name);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("setmealNames",setmealNames);
        map.put("setmealCount",mapList);
        return map;
    }
}
